package tech.yunqian.slim.project.service;

import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.thingsboard.rest.client.RestClient;
import org.thingsboard.server.common.data.EntityType;
import org.thingsboard.server.common.data.id.EntityId;
import org.thingsboard.server.common.data.id.EntityIdFactory;
import org.thingsboard.server.common.data.kv.TsKvEntry;

import lombok.extern.slf4j.Slf4j;
import tech.yunqian.slim.project.domain.ThingsBoardCredentials;

@Slf4j
@Service
public class ThingsBoardService {
    @Value("${thingsboard.url}")
    private String thingsBoardUrl;

    public JSONObject getLatestTimeSeries(ThingsBoardCredentials credentials, String tbDeviceId) {
        JSONObject timeSeries = new JSONObject();
        try {
            RestClient restClient = new RestClient(thingsBoardUrl);
            restClient.login(credentials.getUsername(), credentials.getPassword());
            EntityId entityId = EntityIdFactory.getByTypeAndUuid(EntityType.DEVICE, tbDeviceId);
            List<TsKvEntry> entries = restClient.getLatestTimeseries(entityId, restClient.getTimeseriesKeys(entityId));
            for (TsKvEntry entry : entries) {
                JSONObject item = new JSONObject();
                item.put("value", entry.getValue());
                item.put("ts", entry.getTs());
                timeSeries.put(entry.getKey(), item);
            }
            restClient.close();
        } catch (Exception e) {
            log.info(e.getMessage());
            StackTraceElement[] traces = e.getStackTrace();
            for (StackTraceElement trace : traces) {
                log.debug(trace.toString());
            }
        }
        return timeSeries;
    }

    public Boolean putTelemetries(ThingsBoardCredentials credentials, String tbDeviceId, JSONObject telemetries) {
        Boolean done = false;
        try {
            RestClient restClient = new RestClient(thingsBoardUrl);
            restClient.login(credentials.getUsername(), credentials.getPassword());
            EntityId entityId = EntityIdFactory.getByTypeAndUuid(EntityType.DEVICE, tbDeviceId);
            ObjectMapper mapper = new ObjectMapper();
            JsonNode request = mapper.readTree(telemetries.toJSONString());
            restClient.saveEntityTelemetry(entityId, "LATEST_TS", request);
            restClient.close();
            done = true;
        } catch (Exception e) {
            log.info(e.getMessage());
            StackTraceElement[] traces = e.getStackTrace();
            for (StackTraceElement trace : traces) {
                log.debug(trace.toString());
            }
        }
        return done;
    }
}
